import React, { lazy } from 'react'
import LazyLoad from './lazyLoad';
import store from '@/redux'
import { GlobalTypes } from '@/redux/modules/type';
import { cloneDeep } from 'lodash'
import { setCache } from '@/utils/session';

export interface IRoute {
    name?: string;
    path: string;
    meta: any;
    key?: string;
    type?:string;
    label?: string;
    extendone?: any;
    hidden?: boolean | undefined;
    redirect?: string;
    children?: Array<any> | null;
    element?: React.ReactNode;
    menuType?: string;
    menutype?: string;
    menuName?: string;
    elementpath?: string;
}

let btnPermission: any[] = [];//页面内操作权限，如按钮

//处理路由数据
export const dealRouteData = (permissionBox: Array<any>) => {
    btnPermission = [];
    let result = dealPermissions(permissionBox);
    let menuRouter = filterAsyncRouter(result);
    let accessedRouters = flatAsyncRoutes(menuRouter);

    //更新页面内的操作权限
    store.dispatch({
        type: GlobalTypes.UPDATE_PERMISSION,
        data: btnPermission
    });
    //更新菜单路由权限
    store.dispatch({
        type: GlobalTypes.UPDATE_ROUTES,
        data: menuRouter
    });
    //更新所有页面权限
    store.dispatch({
        type: GlobalTypes.UPDATE_FLAT_ROUTES,
        data: accessedRouters
    })
    let homeRoute = accessedRouters[0];
    homeRoute.element = loadComponent(homeRoute.path, homeRoute.menutype);
    setCache('home',homeRoute);
    //更新首页
    store.dispatch({
        type: GlobalTypes.UPDATE_HOME,
        data: homeRoute
    })

    return {
        btnPermission,
        accessedRouters,
        menuRouter
    }
}

//处理用户菜单中权限信息
export const dealPermissions = (permissionBox: Array<any>) => {
    if (!permissionBox || !permissionBox.length) return [];
    permissionBox.map(item => {
        item.name = item.menuName;
        item.meta = { title: item.menuName, icon: item.icon };
        if (item.menuType == 'M') {
            let res = getFirstMenu(item);
            let path = res.path || '/';
            item.redirect = path;
        }
        if (item.children && item.children.length) {
            item.children = dealPermissions(item.children);
        } else {
            item.children = null;
        }
        if (item.menuType == 'F') {
            btnPermission.push(item.path);
        }
        if (item.menuType == 'C') {
            if (!hasChildren(item)) {
                item.children = null;
            }
            item.hidden = item.extendone == 'false' ? false : true;
        }
    });
    return permissionBox;
}

//路由下是否有有效的路由子集
const hasChildren = (item: IRoute) => {
    if (item.children) {
        let isHas = !item.children.every(item => item.extendone == 'false') || item.children.some(item => item.menuType == 'F')
        if (isHas) {
            return false;
        } else {
            return true
        }
    } else {
        return false;
    }
}
//权限菜单中第一个实质性的菜单
export const getFirstMenu = (item: any): any => {
    if (!item) return {};
    if (item.menuType == 'C') {
        return item;
    }
    if (item.menuType == 'M') {
        let getItem = item?.children.find((menu: any) => menu.menuType == 'C');
        if (getItem) {
            return getFirstMenu(item.children[0]);
        } else {
            return item;
        }
    }
}

//转换
export function filterAsyncRouter(routerMap: Array<any>) {
    const accessedRouters: Array<any> = []
    routerMap.forEach((item: IRoute) => {
        item.meta = item.meta ? item.meta : {};
        let hidden = item.extendone == 'true'
        let path = item.path;
        //MAP转路由对象和权限对象
        let route: IRoute = {
            path: path,
            key: path,
            label: item.menuName,
            meta: item.meta,
            menutype: item.menuType,
            hidden: hidden ? true : false,
            redirect: item.redirect,
            children: item.children ? filterAsyncRouter(item.children) : null,
            element: path,
            elementpath: path
        }
        accessedRouters.push(route)
    })
    return accessedRouters
}

export function loadComponent(component: string, type: string | undefined) {
    // const modules: any = import.meta.glob(['@/views/**/*.tsx', '@/views/**/*.ts'], { eager: true });
    //按钮不需要路由加载
    if (component && type != 'F' && type != "M") {
        let url = `../views${component}`;
        return LazyLoad(lazy(() => import(/* @vite-ignore */url)))
        // return LazyLoad(lazy(modules[`/src/views${component}.tsx`]))
    }
}

// 将多层嵌套路由处理成平级
export function flatAsyncRoutes(routes: Array<IRoute>, breadcrumb: any = []) {
    let res: Array<any> = []
    routes.forEach((route: IRoute) => {
        const tmp = cloneDeep(route)
        if (tmp.children) {
            let childrenBreadcrumb = cloneDeep(breadcrumb)
            childrenBreadcrumb.push(route)
            let tmpRoute = cloneDeep(route)
            tmpRoute.meta.breadcrumb = cloneDeep(childrenBreadcrumb)
            delete tmpRoute.children
            res.push(tmpRoute)
            let childrenRoutes = flatAsyncRoutes(tmp.children, childrenBreadcrumb)
            childrenRoutes.map(item => {
                res.push(item)
            })
        } else {
            let tmpBreadcrumb = cloneDeep(breadcrumb)
            tmpBreadcrumb.push(tmp)
            tmp.meta.breadcrumb = cloneDeep(tmpBreadcrumb)
            res.push(tmp)
        }
    })
    return res
}